var createError = require('http-errors');
var express = require('express');
var cors = require('cors');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var drawingRouter = require('./routes/drawing');
var chatRouter = require('./routes/chat');
var qianFanRouter = require('./routes/qianfan');
var authRouter = require('./routes/auth');
var { authenticateToken } = require('./middleware/authMiddleware');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// 使用CORS中间件，设置允许跨域的配置，你也可以进行更细粒度的配置，例如：
app.use(cors({
  origin: '*', // 只允许这个域名的请求
  methods: ['GET', 'POST'],     // 只允许GET和POST请求
  allowedHeaders: ['Content-Type', 'Authorization'] // 允许这些头部
}));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 对需要认证的路由使用统一认证中间件
app.use('/draw', authenticateToken, drawingRouter);
app.use('/chat', authenticateToken, chatRouter);
app.use('/qianfan', authenticateToken, qianFanRouter);
app.use('/auth', authRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
